﻿using System;
using System.Collections.Generic;
using System.IO ;
using System.Linq;
using System.Security.Cryptography ;
using System.Text;

namespace SugarFineUI.Framework.Uitility
{
    /// <summary>
    /// 加密解密相关安全的工具类
    /// </summary>
    public class Security
    {
        #region MD5
        public class MD5Helper
        {
            /// <summary>
            /// 获得32位的MD5加密
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public static string GetMD5_32(string input)
            {
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sb.Append(data[i].ToString("x2"));
                }
                return sb.ToString();
            }

            /// <summary>
            /// 获得16位的MD5加密
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public static string GetMD5_16(string input)
            {
                return GetMD5_32(input).Substring(8, 16);
            }

            /// <summary>
            /// 获得8位的MD5加密
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public static string GetMD5_8(string input)
            {
                return GetMD5_32(input).Substring(8, 8);
            }

            /// <summary>
            /// 获得4位的MD5加密
            /// </summary>
            /// <param name="input"></param>
            /// <returns></returns>
            public static string GetMD5_4(string input)
            {
                return GetMD5_32(input).Substring(8, 4);
            }

            public static string MD5EncryptHash(String input)
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                //the GetBytes method returns byte array equavalent of a string
                byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), 0, input.Length);
                char[] temp = new char[res.Length];
                //copy to a char array which can be passed to a String constructor
                Array.Copy(res, temp, res.Length);
                //return the result as a string
                return new String(temp);
            }


            /// <summary>
            /// uff8格式的md5
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string GetMD5UTF8(string str)
            {
                byte[] b = Encoding.UTF8.GetBytes(str);
                b = new MD5CryptoServiceProvider().ComputeHash(b);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < b.Length; i++)
                    sb.Append(b[i].ToString("x").PadLeft(2, '0'));
                return sb.ToString();
            }

            /// <summary>
            /// 获取密码的md5
            /// </summary>
            /// <param name="username">用户名</param>
            /// <param name="pwd">密码</param>
            /// <returns></returns>
            public static string GetMd5Pwd(string username, string pwd)
            {
                string info = username + pwd + "61ca4367e82e7f201e37faf6bb4c8b0b"; //加盐值
                return GetMD5UTF8(info);
            }
        }
        #endregion

        #region AES加密解密,和java AES通用
        //参看http://www.cnblogs.com/ahui/archive/2011/04/22/2025045.html 
        /// <summary>
        /// AES加密解密,和java AES通用
        /// </summary>
        public class AES
        {
            #region 成员变量
            /// <summary>  
            /// 密钥(32位,不足在后面补0)  
            /// </summary>  
            //private const string _passwd = "ihlih*0037JOHT*)(PIJY*(()JI^)IO%";
            private const string _passwd = "1234567890123456" ;

            /// <summary>  
            /// 运算模式  
            /// </summary>  
            private static CipherMode _cipherMode = CipherMode.ECB ;

            /// <summary>  
            /// 填充模式  
            /// </summary>  
            private static PaddingMode _paddingMode = PaddingMode.PKCS7 ;

            /// <summary>  
            /// 字符串采用的编码  
            /// </summary>  
            private static Encoding _encoding = Encoding.UTF8 ;

            #endregion

            #region 辅助方法

            /// <summary>  
            /// 获取32byte密钥数据  
            /// </summary>  
            /// <param name="password">密码</param>  
            /// <returns></returns>  
            private static byte[] GetKeyArray(string password)
            {
                if (password == null)
                {
                    password = string.Empty ;
                }

                if (password.Length < 32)
                {
                    password = password.PadRight(32, '0') ;
                }
                else if (password.Length > 32)
                {
                    password = password.Substring(0, 32) ;
                }

                return _encoding.GetBytes(password) ;
            }

            /// <summary>  
            /// 将字符数组转换成字符串  
            /// </summary>  
            /// <param name="inputData"></param>  
            /// <returns></returns>  
            private static string ConvertByteToString(byte[] inputData)
            {
                StringBuilder sb = new StringBuilder(inputData.Length * 2) ;
                foreach (var b in inputData)
                {
                    sb.Append(b.ToString("X2")) ;
                }

                return sb.ToString() ;
            }

            /// <summary>  
            /// 将字符串转换成字符数组  
            /// </summary>  
            /// <param name="inputString"></param>  
            /// <returns></returns>  
            private static byte[] ConvertStringToByte(string inputString)
            {
                if (inputString == null || inputString.Length < 2)
                {
                    throw new ArgumentException() ;
                }

                int l = inputString.Length / 2 ;
                byte[] result = new byte[l] ;
                for (int i = 0; i < l; ++i)
                {
                    result[i] = Convert.ToByte(inputString.Substring(2 * i, 2), 16) ;
                }

                return result ;
            }

            #endregion

            #region AES加密

            /// <summary>  
            /// 加密字节数据  
            /// </summary>  
            /// <param name="inputData">要加密的字节数据</param>  
            /// <param name="keyWord">密码钥匙</param>  
            /// <returns></returns>  
            public static byte[] AESEncrypt(byte[] inputData, string keyWord)
            {
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider() ;
                aes.Key = GetKeyArray(keyWord) ;
                aes.Mode = _cipherMode ;
                aes.Padding = _paddingMode ;
                ICryptoTransform transform = aes.CreateEncryptor() ;
                byte[] data = transform.TransformFinalBlock(inputData, 0, inputData.Length) ;
                aes.Clear() ;
                return data ;
            }

            /// <summary>  
            /// 加密字符串(加密为16进制字符串)  
            /// </summary>  
            /// <param name="inputString">要加密的字符串</param>  
            /// <param name="keyWord">密码钥匙</param>  
            /// <returns></returns>  
            public static string AESEncrypt(string inputString, string keyWord)
            {
                byte[] toEncryptArray = _encoding.GetBytes(inputString) ;
                byte[] result = AESEncrypt(toEncryptArray, keyWord) ;
                return ConvertByteToString(result) ;
            }

            /// <summary>  
            /// 字符串加密(加密为16进制字符串)  
            /// </summary>  
            /// <param name="inputString">需要加密的字符串</param>  
            /// <returns>加密后的字符串</returns>  
            public static string AESEncryptString(string inputString)
            {
                return AESEncrypt(inputString, _passwd) ;
            }

            #endregion

            #region AES解密

            /// <summary>  
            /// 解密字节数组  
            /// </summary>  
            /// <param name="inputData">要解密的字节数据</param>  
            /// <param name="keyWord">密码钥匙</param>  
            /// <returns></returns>  
            public static byte[] AESDecrypt(byte[] inputData, string keyWord)
            {
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider() ;
                aes.Key = GetKeyArray(keyWord) ;
                aes.Mode = _cipherMode ;
                aes.Padding = _paddingMode ;
                ICryptoTransform transform = aes.CreateDecryptor() ;
                byte[] data = null ;
                try
                {
                    data = transform.TransformFinalBlock(inputData, 0, inputData.Length) ;
                }
                catch
                {
                    return null ;
                }

                aes.Clear() ;
                return data ;
            }

            /// <summary>  
            /// 解密16进制的字符串为字符串  
            /// </summary>  
            /// <param name="inputString">要解密的字符串</param>  
            /// <param name="keyWord">密码钥匙</param>  
            /// <returns>字符串</returns>  
            public static string AESDecrypt(string inputString, string keyWord)
            {
                byte[] toDecryptArray = ConvertStringToByte(inputString) ;
                string decryptString = _encoding.GetString(AESDecrypt(toDecryptArray, keyWord)) ;
                return decryptString ;
            }

            /// <summary>  
            /// 解密16进制的字符串为字符串  
            /// </summary>  
            /// <param name="inputString">需要解密的字符串</param>  
            /// <returns>解密后的字符串</returns>  
            public static string AESDecryptString(string inputString)
            {
                return AESDecrypt(inputString, _passwd) ;
            }

            #endregion
        }
        #endregion


        #region 对称加密算法AES RijndaelManaged加密解密
        public class AESHelper
        {
            private const string Default_AES_Key = "www.1024todo.cn@#%^SugarFineUI";

            private static byte[] Keys =
            {
                0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79,
                0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F
            };

            public static string AES_Encrypt(string encryptString)
            {
                return AES_Encrypt(encryptString, Default_AES_Key);
            }

            public static string AES_Decrypt(string decryptString)
            {
                return AES_Decrypt(decryptString, Default_AES_Key);
            }

            /// <summary>对称加密算法AES RijndaelManaged加密(RijndaelManaged（AES）算法是块式加密算法)
            /// 
            /// </summary>
            /// <param name="encryptString">待加密字符串</param>
            /// <param name="encryptKey">加密密钥，须半角字符</param>
            /// <returns>加密结果字符串</returns>
            public static string AES_Encrypt(string encryptString, string encryptKey)
            {
                encryptKey = GetSubString(encryptKey, 32, "");
                encryptKey = encryptKey.PadRight(32, ' ');

                RijndaelManaged rijndaelProvider = new RijndaelManaged();
                rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
                rijndaelProvider.IV = Keys;
                ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();

                byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
                byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);

                return Convert.ToBase64String(encryptedData);
            }


            /// <summary> 对称加密算法AES RijndaelManaged解密字符串
            ///
            /// </summary>
            /// <param name="decryptString">待解密的字符串</param>
            /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
            /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
            public static string AES_Decrypt(string decryptString, string decryptKey)
            {
                try
                {
                    decryptKey = GetSubString(decryptKey, 32, "");
                    decryptKey = decryptKey.PadRight(32, ' ');

                    RijndaelManaged rijndaelProvider = new RijndaelManaged();
                    rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
                    rijndaelProvider.IV = Keys;
                    ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();

                    byte[] inputData = Convert.FromBase64String(decryptString);
                    byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);

                    return Encoding.UTF8.GetString(decryptedData);
                }
                catch
                {
                    return string.Empty;
                }
            }

            /// <summary>
            /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
            /// </summary>
            /// <param name="sourceString">源字符串</param>
            /// <param name="length">所取字符串字节长度</param>
            /// <param name="tailString">附加字符串(当字符串不够长时，尾部所添加的字符串，一般为"...")</param>
            /// <returns>某字符串的一部分</returns>
            private static string GetSubString(string sourceString, int length, string tailString)
            {
                return GetSubString(sourceString, 0, length, tailString);
            }

            /// <summary>
            /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
            /// </summary>
            /// <param name="sourceString">源字符串</param>
            /// <param name="startIndex">索引位置，以0开始</param>
            /// <param name="length">所取字符串字节长度</param>
            /// <param name="tailString">附加字符串(当字符串不够长时，尾部所添加的字符串，一般为"...")</param>
            /// <returns>某字符串的一部分</returns>
            private static string GetSubString(string sourceString, int startIndex, int length, string tailString)
            {
                string myResult = sourceString;

                //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
                if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") ||
                    System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+"))
                {
                    //当截取的起始位置超出字段串长度时
                    if (startIndex >= sourceString.Length)
                    {
                        return string.Empty;
                    }
                    else
                    {
                        return sourceString.Substring(startIndex,
                            ((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length);
                    }
                }

                //中文字符，如"中国人民abcd123"
                if (length <= 0)
                {
                    return string.Empty;
                }
                byte[] bytesSource = Encoding.Default.GetBytes(sourceString);

                //当字符串长度大于起始位置
                if (bytesSource.Length > startIndex)
                {
                    int endIndex = bytesSource.Length;

                    //当要截取的长度在字符串的有效长度范围内
                    if (bytesSource.Length > (startIndex + length))
                    {
                        endIndex = length + startIndex;
                    }
                    else
                    {
                        //当不在有效范围内时,只取到字符串的结尾
                        length = bytesSource.Length - startIndex;
                        tailString = "";
                    }

                    int[] anResultFlag = new int[length];
                    int nFlag = 0;
                    //字节大于127为双字节字符
                    for (int i = startIndex; i < endIndex; i++)
                    {
                        if (bytesSource[i] > 127)
                        {
                            nFlag++;
                            if (nFlag == 3)
                            {
                                nFlag = 1;
                            }
                        }
                        else
                        {
                            nFlag = 0;
                        }
                        anResultFlag[i] = nFlag;
                    }
                    //最后一个字节为双字节字符的一半
                    if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1))
                    {
                        length = length + 1;
                    }

                    byte[] bsResult = new byte[length];
                    Array.Copy(bytesSource, startIndex, bsResult, 0, length);
                    myResult = Encoding.Default.GetString(bsResult);
                    myResult = myResult + tailString;

                    return myResult;
                }

                return string.Empty;

            }

            /// <summary>
            /// 加密文件流
            /// </summary>
            /// <param name="fs"></param>
            /// <returns></returns>
            public static CryptoStream AES_EncryptStrream(FileStream fs, string decryptKey)
            {
                decryptKey = GetSubString(decryptKey, 32, "");
                decryptKey = decryptKey.PadRight(32, ' ');

                RijndaelManaged rijndaelProvider = new RijndaelManaged();
                rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
                rijndaelProvider.IV = Keys;

                ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
                CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
                return cytptostreamEncr;
            }

            /// <summary>
            /// 解密文件流
            /// </summary>
            /// <param name="fs"></param>
            /// <returns></returns>
            public static CryptoStream AES_DecryptStream(FileStream fs, string decryptKey)
            {
                decryptKey = GetSubString(decryptKey, 32, "");
                decryptKey = decryptKey.PadRight(32, ' ');

                RijndaelManaged rijndaelProvider = new RijndaelManaged();
                rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
                rijndaelProvider.IV = Keys;
                ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor();
                CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read);
                return cytptostreamDecr;
            }

            /// <summary>
            /// 对指定文件加密
            /// </summary>
            /// <param name="InputFile"></param>
            /// <param name="OutputFile"></param>
            /// <returns></returns>
            public static bool AES_EncryptFile(string InputFile, string OutputFile)
            {
                try
                {
                    string decryptKey = "www.iqidi.com";

                    FileStream fr = new FileStream(InputFile, FileMode.Open);
                    FileStream fren = new FileStream(OutputFile, FileMode.Create);
                    CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey);
                    byte[] bytearrayinput = new byte[fr.Length];
                    fr.Read(bytearrayinput, 0, bytearrayinput.Length);
                    Enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
                    Enfr.Close();
                    fr.Close();
                    fren.Close();
                }
                catch
                {
                    //文件异常
                    return false;
                }
                return true;
            }

            /// <summary>
            /// 对指定的文件解压缩
            /// </summary>
            /// <param name="InputFile"></param>
            /// <param name="OutputFile"></param>
            /// <returns></returns>
            public static bool AES_DecryptFile(string InputFile, string OutputFile)
            {
                try
                {
                    string decryptKey = "www.iqidi.com";
                    FileStream fr = new FileStream(InputFile, FileMode.Open);
                    FileStream frde = new FileStream(OutputFile, FileMode.Create);
                    CryptoStream Defr = AES_DecryptStream(fr, decryptKey);
                    byte[] bytearrayoutput = new byte[1024];
                    int m_count = 0;

                    do
                    {
                        m_count = Defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);
                        frde.Write(bytearrayoutput, 0, m_count);
                        if (m_count < bytearrayoutput.Length)
                            break;
                    } while (true);

                    Defr.Close();
                    fr.Close();
                    frde.Close();
                }
                catch
                {
                    //文件异常
                    return false;
                }
                return true;
            }
        }

        #endregion

        #region DES对称加密解密
        public class DESHelper
        {
            /// <summary> 加密字符串
            /// </summary> 
            /// <param name="strText">需被加密的字符串</param> 
            /// <param name="strEncrKey">密钥</param> 
            /// <returns></returns> 
            public static string DesEncrypt(string strText, string strEncrKey)
            {
                try
                {
                    byte[] byKey = null;
                    byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

                    byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
                    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                    byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                    MemoryStream ms = new MemoryStream();
                    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    return Convert.ToBase64String(ms.ToArray());
                }
                catch
                {
                    return "";
                }
            }

            /// <summary> 解密字符串
            /// </summary> 
            /// <param name="strText">需被解密的字符串</param> 
            /// <param name="sDecrKey">密钥</param> 
            /// <returns></returns> 
            public static string DesDecrypt(string strText, string sDecrKey)
            {
                try
                {
                    byte[] byKey = null;
                    byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                    byte[] inputByteArray = new Byte[strText.Length];

                    byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
                    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                    inputByteArray = Convert.FromBase64String(strText);
                    MemoryStream ms = new MemoryStream();
                    CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    Encoding encoding = new UTF8Encoding();
                    return encoding.GetString(ms.ToArray());
                }
                catch
                {
                    return null;
                }
            }

            /// <summary> 加密文件
            ///
            /// </summary> 
            /// <param name="m_InFilePath">原路径</param> 
            /// <param name="m_OutFilePath">加密后的文件路径</param> 
            /// <param name="strEncrKey">密钥</param> 
            public static void DesEncryptFile(string m_InFilePath, string m_OutFilePath, string strEncrKey)
            {
                try
                {
                    byte[] byKey = null;
                    byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

                    byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
                    FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
                    FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
                    fout.SetLength(0);
                    //Create variables to help with read and write. 
                    byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
                    long rdlen = 0; //This is the total number of bytes written. 
                    long totlen = fin.Length; //This is the total length of the input file. 
                    int len; //This is the number of bytes to be written at a time.

                    DES des = new DESCryptoServiceProvider();
                    CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);

                    //Read from the input file, then encrypt and write to the output file. 
                    while (rdlen < totlen)
                    {
                        len = fin.Read(bin, 0, 100);
                        encStream.Write(bin, 0, len);
                        rdlen = rdlen + len;
                    }
                    encStream.Close();
                    fout.Close();
                    fin.Close();
                }
                catch
                {
                }

            }

            /// <summary> 解密文件
            /// 
            /// </summary> 
            /// <param name="m_InFilePath">被解密路径</param> 
            /// <param name="m_OutFilePath">解密后的路径</param> 
            /// <param name="sDecrKey">密钥</param> 
            public static void DesDecryptFile(string m_InFilePath, string m_OutFilePath, string sDecrKey)
            {
                try
                {
                    byte[] byKey = null;
                    byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

                    byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
                    FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
                    FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
                    fout.SetLength(0);
                    //Create variables to help with read and write. 
                    byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
                    long rdlen = 0; //This is the total number of bytes written. 
                    long totlen = fin.Length; //This is the total length of the input file. 
                    int len; //This is the number of bytes to be written at a time.

                    DES des = new DESCryptoServiceProvider();
                    CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

                    //Read from the input file, then encrypt and write to the output file. 
                    while (rdlen < totlen)
                    {
                        len = fin.Read(bin, 0, 100);
                        encStream.Write(bin, 0, len);
                        rdlen = rdlen + len;
                    }
                    encStream.Close();
                    fout.Close();
                    fin.Close();
                }
                catch
                {
                }
            }
        }
        #endregion

        #region Base64

        public class Base64
        {
            /// <summary>
            /// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
            /// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ，
            /// 這樣共有62個字元，用來作為開始的64個數字，最後兩個用來作為數字的符號在不同的
            /// 系統中而不同。
            /// Base64加密
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string Base64Encrypt(string str)
            {
                byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
                return Convert.ToBase64String(encbuff);
            }

            /// <summary>
            /// Base64解密
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string Base64Decrypt(string str)
            {
                byte[] decbuff = Convert.FromBase64String(str);
                return System.Text.Encoding.UTF8.GetString(decbuff);
            }
        }
        #endregion

        #region  SHA256加密算法
        public class SHA256Helper
        {

            /// <summary>
            /// SHA256函数
            /// </summary>
            /// <param name="str">原始字符串</param>
            /// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
            public static string SHA256(string str)
            {
                byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
                SHA256Managed Sha256 = new SHA256Managed();
                byte[] Result = Sha256.ComputeHash(SHA256Data);
                return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
            }
        }
        #endregion

        #region RSA加密 解密

        public class RSAHelper
        {

            /// <summary>
            /// RSA加密
            /// </summary>
            /// <param name="plaintext">明文</param>
            /// <param name="publicKey">公钥</param>
            /// <returns>密文字符串</returns>
            public static string EncryptByRSA(string plaintext, string publicKey)
            {
                try
                {
                    UnicodeEncoding ByteConverter = new UnicodeEncoding();
                    byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSA.FromXmlString(publicKey);
                        byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
                        return Convert.ToBase64String(encryptedData);
                    }
                }
                catch (Exception)
                {
                    return null;
                }

            }


            /// <summary> 
            /// RSA解密
            /// </summary>
            /// <param name="ciphertext">密文</param>
            /// <param name="privateKey">私钥</param>
            /// <returns>明文字符串</returns>
            public static string DecryptByRSA(string ciphertext, string privateKey)
            {
                try
                {
                    UnicodeEncoding byteConverter = new UnicodeEncoding();
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSA.FromXmlString(privateKey);
                        byte[] encryptedData = Convert.FromBase64String(ciphertext);
                        byte[] decryptedData = RSA.Decrypt(encryptedData, false);
                        return byteConverter.GetString(decryptedData);
                    }
                }
                catch (Exception)
                {
                    return null;
                }
            }

            /// <summary>生成RSA加密 解密的 密钥
            /// 生成的key就是 方法EncryptByRSA与DecryptByRSA用的key了
            /// </summary>
            /// <param name="path">要生成的密钥文件的路径(文件夹)</param>
            public static void getRSAKey(string path)
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                string datetimestr = System.DateTime.Now.ToString("yyyyMMddHHmmss");
                using (StreamWriter writer = new StreamWriter("RSA解密_PrivateKey_" + datetimestr + ".xml")) //这个文件要保密...
                {
                    writer.WriteLine(rsa.ToXmlString(true));
                }
                using (StreamWriter writer = new StreamWriter("RSA加密_PublicKey_" + datetimestr + ".xml"))
                {
                    writer.WriteLine(rsa.ToXmlString(false));
                }
            }
        }
        #endregion

        #region RC4加密 解密

        public class RC4Helper
        {
            /// <summary>RC4加密算法
            /// 返回进过rc4加密过的字符
            /// </summary>
            /// <param name="str">被加密的字符</param>
            /// <param name="ckey">密钥</param>
            public static string EncryptRC4wq(string str, string ckey)
            {
                int[] s = new int[256];
                for (int i = 0; i < 256; i++)
                {
                    s[i] = i;
                }
                //密钥转数组
                char[] keys = ckey.ToCharArray(); //密钥转字符数组
                int[] key = new int[keys.Length];
                for (int i = 0; i < keys.Length; i++)
                {
                    key[i] = keys[i];
                }
                //明文转数组
                char[] datas = str.ToCharArray();
                int[] mingwen = new int[datas.Length];
                for (int i = 0; i < datas.Length; i++)
                {
                    mingwen[i] = datas[i];
                }

                //通过循环得到256位的数组(密钥)
                int j = 0;
                int k = 0;
                int length = key.Length;
                int a;
                for (int i = 0; i < 256; i++)
                {
                    a = s[i];
                    j = (j + a + key[k]);
                    if (j >= 256)
                    {
                        j = j % 256;
                    }
                    s[i] = s[j];
                    s[j] = a;
                    if (++k >= length)
                    {
                        k = 0;
                    }
                }
                //根据上面的256的密钥数组 和 明文得到密文数组
                int x = 0, y = 0, a2, b, c;
                int length2 = mingwen.Length;
                int[] miwen = new int[length2];
                for (int i = 0; i < length2; i++)
                {
                    x = x + 1;
                    x = x % 256;
                    a2 = s[x];
                    y = y + a2;
                    y = y % 256;
                    s[x] = b = s[y];
                    s[y] = a2;
                    c = a2 + b;
                    c = c % 256;
                    miwen[i] = mingwen[i] ^ s[c];
                }
                //密文数组转密文字符
                char[] mi = new char[miwen.Length];
                for (int i = 0; i < miwen.Length; i++)
                {
                    mi[i] = (char)miwen[i];
                }
                string miwenstr = new string(mi);
                return miwenstr;
            }

            /// <summary>RC4解密算法
            /// 返回进过rc4解密过的字符
            /// </summary>
            /// <param name="str">被解密的字符</param>
            /// <param name="ckey">密钥</param>
            public static string DecryptRC4wq(string str, string ckey)
            {
                int[] s = new int[256];
                for (int i = 0; i < 256; i++)
                {
                    s[i] = i;
                }
                //密钥转数组
                char[] keys = ckey.ToCharArray(); //密钥转字符数组
                int[] key = new int[keys.Length];
                for (int i = 0; i < keys.Length; i++)
                {
                    key[i] = keys[i];
                }
                //密文转数组
                char[] datas = str.ToCharArray();
                int[] miwen = new int[datas.Length];
                for (int i = 0; i < datas.Length; i++)
                {
                    miwen[i] = datas[i];
                }

                //通过循环得到256位的数组(密钥)
                int j = 0;
                int k = 0;
                int length = key.Length;
                int a;
                for (int i = 0; i < 256; i++)
                {
                    a = s[i];
                    j = (j + a + key[k]);
                    if (j >= 256)
                    {
                        j = j % 256;
                    }
                    s[i] = s[j];
                    s[j] = a;
                    if (++k >= length)
                    {
                        k = 0;
                    }
                }
                //根据上面的256的密钥数组 和 密文得到明文数组
                int x = 0, y = 0, a2, b, c;
                int length2 = miwen.Length;
                int[] mingwen = new int[length2];
                for (int i = 0; i < length2; i++)
                {
                    x = x + 1;
                    x = x % 256;
                    a2 = s[x];
                    y = y + a2;
                    y = y % 256;
                    s[x] = b = s[y];
                    s[y] = a2;
                    c = a2 + b;
                    c = c % 256;
                    mingwen[i] = miwen[i] ^ s[c];
                }
                //明文数组转明文字符
                char[] ming = new char[mingwen.Length];
                for (int i = 0; i < mingwen.Length; i++)
                {
                    ming[i] = (char)mingwen[i];
                }
                string mingwenstr = new string(ming);
                return mingwenstr;
            }
        }

        #endregion

    }
}
